package com.example.myandroidtest.ui.surface;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.util.Objects;

public class SurfaceViewTemplate extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder mSurfaceHolder;
    private Canvas mCanvas;
    // 子线程是否正在绘制的标识
    private boolean mIsDrawing;

    // 初始化
    private void initView() {
        mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
        setFocusable(true);
        setKeepScreenOn(true);
        setFocusableInTouchMode(true);
    }

    public SurfaceViewTemplate(Context context) {
        this(context, null, 0);
    }

    public SurfaceViewTemplate(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SurfaceViewTemplate(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 执行初始化
        initView();
    }

    // 创建
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        this.mIsDrawing = true;
        // 开启子线程执行绘图逻辑
        new Thread(this).start();
    }

    // 改变
    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    // 销毁
    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        this.mIsDrawing = false;
    }

    // 在子线程中执行绘图逻辑
    @Override
    public void run() {
        while (mIsDrawing) {
            draw();
        }
    }

    private void draw() {
        try {
            // 获得Canvas对象
            mCanvas = mSurfaceHolder.lockCanvas();
            // 绘制背景
            mCanvas.drawColor(Color.WHITE);
            // 其余绘图逻辑

        } catch (Exception e) {
            Log.d("SurfaceView exception: ", Objects.requireNonNull(e.getMessage()));
        } finally {
            if (mCanvas != null) {
                // 释放Canvas对象并且提交画布
                mSurfaceHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }
}
